package com.example.demo.schedule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2021年06⽉11⽇<br/>
 * @version：v1.0.0<br>
 */
@RestController
@Component
public class DynamicTask {

    public static Map<String,ScheduledFuture> scheduledFutureMap = new HashMap<>();

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    @RequestMapping("/startCron")
    public String startCron() {
        ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger("0/5 * * * * *"));
        ScheduledFuture<?> future2 = threadPoolTaskScheduler.schedule(new MyRunnable2(), new CronTrigger("0/10 * * * * *"));
        scheduledFutureMap.put("task1",future);
        scheduledFutureMap.put("task2",future2);
        System.out.println("DynamicTask.startCron()");
        return "startCron";
    }

    @RequestMapping("/stopCron")
    public String stopCron() {
        scheduledFutureMap.forEach((key,value)->{
            if(Objects.nonNull(value)){
                value.cancel(true);
            }
        });
        System.out.println("DynamicTask.stopCron()");
        return "stopCron";
    }

    @RequestMapping("/stopCron10")
    public String stopCron10() {
        scheduledFutureMap.forEach((key,value)->{
            if(key.equals("task2")){
                if(Objects.nonNull(value)){
                    value.cancel(true);
                }
            }
        });
        return "stopCron10 success";
    }

    private class MyRunnable implements Runnable {

        @Override
        public void run() {
            System.out.println("DynamicTask-1.MyRunnable.run()，" + new Date());
        }
    }

    private class MyRunnable2 implements Runnable {

        @Override
        public void run() {
            System.out.println("DynamicTask-2.MyRunnable.run()，" + new Date());
        }
    }
}
